package com.zby.business.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.util.LruCache;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.zby.business.R;
import com.zby.business.activity.Detail;
import com.zby.business.adapter.ImagePagerAdapter;
import com.zby.business.net.MyAsyncTask;
import com.zby.business.util.App;
import com.zby.business.util.Util;
import com.zby.business.util.ViewPagerScroller;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by BY on 2015/12/29.
 */
public class ShouYeFragment extends Fragment implements View.OnClickListener {
    private View view;
    private LinearLayout searchLayout, messageLayout, container1, container2;
    private ImageView voiceImage;
    private FragmentManager Fm;
    private SearchFragment searchFragment;
    private FragmentTransaction Ft;
    private ViewPager viewPager;
    private int[] images = {R.mipmap.apple08large, R.mipmap.chocolatelarge3, R.mipmap.fishlarge3, R.mipmap.shrimplarge2};
    private LinearLayout linearLayout;
    private Handler handler = new Handler();
    private Field field;
    private ViewPagerScroller viewPagerScroller;
    private LayoutInflater inflater;
    private ArrayList commodityPrice, commodityName, commoditypicture, commodityIntroduce, commodityDetailId, commoditySale, commodityDiscount;
    private ImageLoader imageLoader;
    private LruCache cache;
    private App app;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.shouye, null);
        init();
        initData();
        getData();
        return view;
    }

    private boolean FingerDown = false;
    private long time;

    private void initData() {
        ImagePagerAdapter imagePagerAdapter = new ImagePagerAdapter(images, getContext(), new String[]{});
        viewPager.setAdapter(imagePagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                linearLayout.removeAllViews();
                for (int i = 0; i < images.length; i++) {
                    ImageView imageView = new ImageView(getContext());
                    if (i == position % images.length) {
                        imageView.setBackgroundResource(R.mipmap.moon);
                    } else {
                        imageView.setBackgroundResource(R.mipmap.white_cicle);
                    }
                    linearLayout.addView(imageView);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        FingerDown = true;
                        break;
                    case MotionEvent.ACTION_UP:
                        time = System.currentTimeMillis();
                        viewPagerScroller.setDuration(200);
                        try {
                            field.set(viewPager, viewPagerScroller);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                        FingerDown = false;
                        break;
                }
                return false;
            }
        });
        try {
            field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            viewPagerScroller = new ViewPagerScroller(viewPager.getContext(), new AccelerateInterpolator());
            field.set(viewPager, viewPagerScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        viewPager.setCurrentItem(Integer.MAX_VALUE / images.length / 2 * images.length);
//        System.out.println("current index:" + Integer.MAX_VALUE / images.length / 2 * images.length);
        new ImageScrollThread().start();
    }

    private void clearCommodity() {
        commodityDetailId.clear();
        commodityName.clear();
        commodityPrice.clear();
        commoditypicture.clear();
        commodityIntroduce.clear();
        commoditySale.clear();
        commodityDiscount.clear();
    }

    private void init() {
        app = (App) getActivity().getApplication();
        imageLoader = ImageLoader.getInstance();
        ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(getContext());
        imageLoader.init(config);
        cache = new LruCache((int) (Runtime.getRuntime().maxMemory() / 20));
        Fm = getFragmentManager();
        commodityName = new ArrayList();
        commoditypicture = new ArrayList();
        commodityPrice = new ArrayList();
        commodityIntroduce = new ArrayList();
        commodityDetailId = new ArrayList();
        commoditySale = new ArrayList();
        commodityDiscount = new ArrayList();
        inflater = LayoutInflater.from(getContext());
        searchLayout = (LinearLayout) view.findViewById(R.id.searchLinearLayout);
        messageLayout = (LinearLayout) view.findViewById(R.id.MyMessageLayOut);
        container1 = (LinearLayout) view.findViewById(R.id.container1);
        container2 = (LinearLayout) view.findViewById(R.id.container2);
        voiceImage = (ImageView) view.findViewById(R.id.voiceImage);
        viewPager = (ViewPager) view.findViewById(R.id.viewpager);
        linearLayout = (LinearLayout) view.findViewById(R.id.imagePagerIndexLayout);
        voiceImage.setOnClickListener(this);
        searchLayout.setOnClickListener(this);
        messageLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Ft = Fm.beginTransaction();
        switch (v.getId()) {
            case R.id.searchLinearLayout:
                if (searchFragment == null) {
                    searchFragment = new SearchFragment();
                    Ft.add(searchFragment, "SEARCH");
                }
                Ft.replace(R.id.mainFrame, searchFragment);
                Ft.addToBackStack(null);
                break;
        }
        Ft.commit();
    }

    @Override
    public void onResume() {
        getData();
        super.onResume();
    }

    public void getData() {
        MyAsyncTask task = new MyAsyncTask();
        try {
            String s = task.execute("getDiscount").get();
            System.out.println(s);
            JSONObject json = new JSONObject(s);
            JSONArray details = json.getJSONArray("commodityDetails");
            if (details.length() > 0) {
                clearCommodity();
                container1.removeAllViews();
                container2.removeAllViews();
                for (int i = 0; i < details.length(); i++) {
                    JSONObject commodity = (JSONObject) details.get(i);
                    commodityDetailId.add(commodity.get("commodityDetailId"));
                    commodityName.add(commodity.get("commodityBrand"));
                    commodityPrice.add(commodity.get("commodityPrice"));
                    commoditypicture.add(commodity.get("commodityPicture"));
                    commodityIntroduce.add(commodity.get("commodityIntroduce"));
                    commoditySale.add(commodity.get("commoditySale"));
                    commodityDiscount.add(commodity.get("discount"));
                }
            }
            TextView price, discountPrice, name;
            ImageView image;
            ImageView addToCar;
            for (int j = 0; j < details.length(); j++) {
                View view = inflater.inflate(R.layout.discount, null);
                price = (TextView) view.findViewById(R.id.price);
                discountPrice = (TextView) view.findViewById(R.id.discoutPrice);
                name = (TextView) view.findViewById(R.id.name);
                image = (ImageView) view.findViewById(R.id.image);
                addToCar = (ImageView) view.findViewById(R.id.addToCar);
                final int finalJ = j;
                String[] p = (Float.parseFloat(commodityPrice.get(j) + "") * Float.parseFloat(commodityDiscount.get(j) + "") + "").split("\\.");
                String l;
                if (p[1].length() > 2) {
                    l = p[1].substring(0, 2);
                } else {
                    l = p[1];
                }
                final String Price = p[0] + "." + l;
                discountPrice.setText(Price);
                addToCar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!app.getUserId().equals("")) {
                            MyAsyncTask asyncTask = new MyAsyncTask();
                            try {
                                String s = asyncTask.execute("phoneAddToCar?detailId=" + commodityDetailId.get(finalJ) + "&userId=" + app.getUserId() + "&price=" + Price + "&number=1").get();
                                if (s.equals("success")) {
                                    Util.toast(getContext(), "保存成功");
                                } else {
                                    Util.toast(getContext(), "保存失败");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Util.toast(getContext(), "保存失败");
                            }
                        } else {
                            Util.toast(getContext(), "请先登录");
                        }
                    }
                });
                price.setText(commodityPrice.get(j) + "");
                price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

                name.setText(commodityName.get(j) + "");
                final String[] url = commoditypicture.get(j).toString().split("\\;");
                Bitmap bitmap = (Bitmap) cache.get(url[0]);
                if (bitmap != null) {
                    image.setImageBitmap(bitmap);
                } else {
                    final ImageView finalImage = image;
                    imageLoader.loadImage(Util.BASE_URL + url[0], new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {

                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                            finalImage.setImageBitmap(bitmap);
                            cache.put(url[0], bitmap);
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });
                }
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), Detail.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("introduce", commodityIntroduce.get(finalJ) + "");
                        bundle.putString("price", Price);
                        bundle.putString("sale", commoditySale.get(finalJ) + "");
                        bundle.putString("commodityId", commodityDetailId.get(finalJ) + "");
                        bundle.putString("url", commoditypicture.get(finalJ) + "");
                        intent.putExtra("bundle", bundle);
                        startActivity(intent);
                    }
                });
                if (j % 2 == 0) {
                    container1.addView(view);
                } else {
                    container2.addView(view);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ImageScrollThread extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(5000);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (FingerDown == false) {
                                if (System.currentTimeMillis() - time > 500)
                                    viewPagerScroller.setDuration(800);
                                try {
                                    field.set(viewPager, viewPagerScroller);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
